#ifndef CONNECTION_H
#define CONNECTION_H

#include <boost/asio.hpp>
#include <google/protobuf/message.h>
#include <memory>
#include <chrono>
#include <atomic>
#include "message_processor.h"

class Connection : public std::enable_shared_from_this<Connection> {
public:
    Connection(boost::asio::io_context& io_context);
    ~Connection();

    boost::asio::ip::tcp::socket& socket();
    void start();
    void stop();
    void reconnect();

    // 发送消息
    void send(const google::protobuf::Message& msg);

    // 设置消息处理器
    void set_message_processor(MessageProcessor* processor); 

private:
    void read_length();
    void read_proto_msg();
    void write(const std::string& data);
    void handle_read(const boost::system::error_code& error, size_t length);
    void handle_write(const boost::system::error_code& error);
    void handle_reconnect();

    boost::asio::ip::tcp::socket socket_;
    uint32_t msg_length_;
    std::unique_ptr<char[]> buffer_;
    std::atomic<bool> is_reconnecting_{false};
    std::chrono::steady_clock::time_point reconnect_start_time_;
    MessageProcessor* message_processor_;
};

#endif